<template>
	<view>
		<view class="scroll-Y">
			<view class="header" :style="{height: height + 62 + 'px'}">
				<u-gap :height="height"></u-gap>
				<view class="header-content" :style="{height: h + 'px',top: top + 'px'}">
					<view class="header-content-layout">
						<u-icon name="arrow-left" color="#30323B" size="22" @click="goBack()"></u-icon>
					</view>

					<view class="header-content-title">
						<view class="header-content-title-tx">{{info.list.user_notes_nickname || ''}}</view>
						<view class="header-content-title-subTitle">{{info.list.name}}</view>
					</view>
					<view class="header-content-layout"></view>
				</view>
				<view class="header-tab">
					<view class="header-tab-list" @click="setPhone">
						<image :src="ossUrl + `/static/wxChat/电话联系.png`" mode=""></image>
						电话联系
					</view>
					<view class="header-tab-list" @click="copy">
						<image :src="ossUrl + `/static/wxChat/微信.png`" mode=""></image>
						加微信
					</view>
					<view class="header-tab-list" @click="open">
						<image :src="ossUrl + `/static/wxChat/备注.png`" mode=""></image>
						备注名
					</view>
				</view>
			</view>
			<view :style="{width: '100%',height: height + 62 + 'px'}"></view>
			<!-- <view class="tips color_fff size_12 align_c" :class="{ 'show':ajax.loading }" @tap="getHistoryMsg"
				:style="{top: height + 62 + 'px'}">{{ajax.loadText}}</view> -->
			<view class="box-1" id="list-box">
				<view class="talk-list" :style="{paddingBottom:bottom ? bottom + 'px' : '10rpx'}">
					<view v-for="(item,index) in talkList" :key="index" :id="`msg-${item.id}`">
						<view class="item flex_col" :class=" item.type == 1 ? 'push':'pull' ">
							<image :src="item.pic" mode="aspectFill" class="pic"></image>
							<view class="content" @longpress="setchshow(item)">
								<rich-text :nodes="replaceEmoji(item.content)"></rich-text>
								<!-- 	<view class="ch" v-if="item.chshow">
									<view class="sxj"></view>
									<view class="chbox">撤回</view>
								</view> -->
							</view>
						</view>
					</view>
					<view id="gd"></view>
				</view>
			</view>
			<view class="box-2" :style="{bottom: keyboardHeight + 'px'}">
				<view class="flex_col">
					<view class="flex_grow input">
						<input type="text" class="content" :adjust-position="false" @focus="foc" :focus="focus"
							v-model="content" placeholder="请输入聊天内容" placeholder-style="color:#DDD;"
							:cursor-spacing="30">
						<!-- <button class="send" @tap="send">发送</button> -->
						<image :src="ossUrl + `/static/wxChat/表情1.png`" class="expression" @click="openShow"></image>
						<image :src="ossUrl + `/static/wxChat/1.png`" mode="" class="send" @tap="send"></image>
					</view>
				</view>
				<view v-if="showPannel">
					<swiper class="emoji-swiper" indicator-dots="true" duration="150">
						<swiper-item v-for="(page,pid) in emojiList" :key="pid">
							<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
								<image mode="widthFix" :src="ossUrl + '/static/img/emoji/'+em.url"></image>
							</view>
						</swiper-item>
					</swiper>
				</view>

			</view>
			<u-modal :show="show" title="修改备注" @cancel="close" @confirm="confirm" ref="uModal" :asyncClose="true"
				:showCancelButton="true">
				<view class="slot-content">
					<view>备注名：</view>
					<u--input placeholder="请输入内容" border="surround" v-model="value" @change="change"></u--input>
				</view>
			</u-modal>


			<u-popup :show="showTree" mode="center" :safeAreaInsetBottom="false" @close="showTree = false"
				bgColor="transparent" :round="20" :overlayOpacity='0.7'>
				<view class="slot-content st2">
					<view class="longan"><text>长按识别二维码</text> </view>
					<view class="slot-content-img">
						<image :src="info.list.WeChat_QR_code?info.list.WeChat_QR_code:''" mode="widthFix"
							:show-menu-by-longpress="true"></image>
					</view>
				</view>
			</u-popup>


		</view>
	</view>
</template>

<script>
	import {
		emojiList,
		replaceEmoji
	} from '@/common/emoji.js'
	import {
		InformationGetChatHistory,InformationdelChat,
		InformationSendMessage,
		InformationNotes
	} from '@/common/http/api.js'
	export default {
		data() {
			return {
				talkList: [],
				showTree: false,
				ajax: {
					rows: 20, //每页数量
					page: 1, //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息'
				},
				content: '',
				top: 0,
				height: 0,
				h: 0,
				//表情
				showPannel: false,
				focus: false,
				emojiList,
				id: '',
				info: '',
				messages_count: 0,
				timer: null,
				bottom: 0,
				show: false,
				value: '',
				scrollIntoView: '',
				keyboardHeight: 0,
				circle_id: 0
			}
		},
		async created() {
			// 获取胶囊按钮的位置信息
			let menuButtonRect = wx.getMenuButtonBoundingClientRect();

			this.top = menuButtonRect.top
			this.height = menuButtonRect.top + menuButtonRect.height + 12
			this.h = menuButtonRect.height

			const sysInfo = await wx.getWindowInfo()
			console.log('sysInfo', sysInfo)
			this.bottom = (sysInfo.screenHeight - sysInfo.safeArea.bottom) * (750 / sysInfo.windowWidth)
			setTimeout(() => {

				// this.scrollIntoView = 'gd'
			}, 3000)
		},
		onLoad(e) {
			clearInterval(this.timer)
			this.id = e.id
			this.circle_id = e.circle_id
			this.$nextTick(() => {
				this.getHistoryMsg();
			});
			//获取消息
			this.timer = setInterval(() => {
				InformationGetChatHistory({
					id: this.id,
					page: this.ajax.page,
					circle_id: this.circle_id
				}).then(res => {
					this.info = res.data
					if (res.data.messages_count > 0) {
						if (this.messages_count != res.data.messages_count) {
							this.showPannel = false
							this.ajax.flag = true
							this.ajax.page = 1

							this.getHistoryMsg().then(res => {
								this.$nextTick(() => {
									// 清空内容框中的内容
									// this.content = '';
									// uni.pageScrollTo({
									// 	scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
									// 	duration: 0
									// });
								})
							})
						}
						this.messages_count = res.data.messages_count
					}
				})
			}, 2000)

			uni.onKeyboardHeightChange(this.getKeyboard)
		},
		onUnload() {
			clearInterval(this.timer)
			uni.offKeyboardHeightChange(this.getKeyboard) // 需传入与监听时同一个的函数对象
		},
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				this.getHistoryMsg();
			}
		},
		methods: {

			isWithinThirtyMinutes(targetTime) {
				// 获取当前时间
				const now = new Date();

				// 将目标时间字符串转换为Date对象
				const target = new Date(targetTime);

				// 计算两个时间之间的差值（毫秒）
				const diff = Math.abs(now - target);

				// 将差值转换为分钟
				const diffInMinutes = diff / (1000 * 60);

				// 判断是否在30分钟之内
				return diffInMinutes <= 30;
			},


			setchshow(e) {
				let targetTimeString = this.isWithinThirtyMinutes(e.created_at)
				if (e.type == 1 && targetTimeString) {
					uni.showActionSheet({
						itemList: ['撤回'],
						itemColor: '#00B66F',
						success: (res) => {
							if (res.tapIndex == 0) {
								InformationdelChat({id:e.id}).then(ress=>{
									this.ajax.flag = true
									this.getHistoryMsg()
									this.$forceUpdate()
								})
							}
						},
						fail: function(res) {
							console.log(res.errMsg);
						}
					});
				}
			},
			close() {
				this.show = false
			},
			//监听键盘
			getKeyboard(res) {

				this.keyboardHeight = res.height || 0
			},
			setScrollIntoView() {
				// this.scrollIntoView = ''
				// this.$nextTick(()=>{
				// 	this.scrollIntoView = 'gd'
				// })
				uni.pageScrollTo({
					scrollTop: 9999999, // -30 为多显示出大半个消息的高度，示意上面还有信息。
					duration: 0
				});
			},
			open() {
				this.value = this.info.list.user_notes_nickname
				this.show = true
			},
			confirm() {
				InformationNotes({
					id: this.id,
					nickname: this.value
				}).then(res => {
					uni.showToast({
						duration: 3000,
						title: "修改成功",
						icon: 'none'
					})
				}).finally(err => {
					this.show = false
				})
			},
			// 表情
			// 展示表情
			openShow() {
				this.showPannel = !this.showPannel;
			},
			//添加表情
			addEmoji(em) {
				this.content += em.alt;
			},
			//替换表情符号为图片
			replaceEmoji,
			// 光标触发隐藏表情
			foc() {
				console.log('foc')
				this.showPannel = false
			},
			// 获取历史消息
			async getHistoryMsg() {

				if (!this.ajax.flag) {
					return; //
				}
				this.hideLoadTips();
				this.ajax.flag = false;
				let data = await this.joinHistoryMsg();

				// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
				let selector = '';

				if (this.ajax.page > 1) {
					// 非第一页，则取历史消息数据的第一条信息元素
					selector = `#msg-${this.talkList[0].id}`;
				} else {
					// 第一页，则取当前消息数据的最后一条信息元素
					selector = `#msg-${data[data.length-1].id}`;
				}
				if (this.ajax.page === 1) {
					this.talkList = data;
				} else {
					this.talkList = [...data, ...this.talkList];
				}
				// 将获取到的消息数据合并到消息数组中


				// 数据挂载后执行，不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
				this.$nextTick(() => {
					// 设置当前滚动的位置
					this.setPageScrollTo(selector);

					this.hideLoadTips(true);

					if (data.length < this.ajax.rows) {
						// 当前消息数据条数小于请求要求条数时，则无更多消息，不再允许请求。
						// 可在此处编写无更多消息数据时的逻辑
					} else {
						this.ajax.page++;

						// 延迟 200ms ，以保证设置窗口滚动已完成
						setTimeout(() => {
							this.ajax.flag = true;
						}, 200)
					}

				})
			},
			// 拼接历史记录消息，正式项目可替换为请求历史记录接口
			async joinHistoryMsg() {
				const res = await InformationGetChatHistory({
					id: this.id,
					page: this.ajax.page,
					circle_id: this.circle_id
				})
				this.info = res.data
				let arr = res.data.messages.map(i => ({
					'created_at': i.created_at,
					"id": i.id, // 消息的ID
					"content": i.message, // 消息内容
					"type": i.sender_id == this.id ? 0 : 1, // 此为消息类别，设 1 为发出去的消息，0 为收到对方的消息,
					"pic": i.sender_id == this.id ? i.friendId : i.user_head // 头像
				}));
				arr.reverse();
				return arr
			},
			// 设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				console.log('view', view)
				view.boundingClientRect((res) => {
					// uni.pageScrollTo({
					// 	scrollTop: 9999999, // -30 为多显示出大半个消息的高度，示意上面还有信息。
					// 	duration: 0
					// });
					this.setScrollIntoView()
				}).exec();
			},
			// 隐藏加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.ajax.loadText = '消息获取成功';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				} else {
					this.ajax.loading = true;
					this.ajax.loadText = '正在获取消息';
				}
			},
			// 发送信息
			send() {
				if (!this.content) {
					uni.showToast({
						duration: 3000,
						title: '请输入有效的内容',
						icon: 'none'
					})
					return;
				}

				uni.showLoading({
					title: '正在发送'
				})
				InformationSendMessage({
					message: this.content,
					id: this.id
				}).then(res => {

					uni.hideLoading()
					// // 将当前发送信息 添加到消息列表。
					// let data = {
					// 	"id": new Date().getTime(),
					// 	"content": this.content,
					// 	"type": 1,
					// 	"pic": "/static/logo.png`"
					// }
					// this.talkList.push(data);
					this.showPannel = false
					this.ajax.flag = true
					this.ajax.page = 1
					//this.talkList = []
					this.getHistoryMsg().then(res => {
						this.content = '';
						this.$nextTick(() => {
							// 清空内容框中的内容
							this.content = '';
							// uni.pageScrollTo({
							// 	scrollTop: 99999999, // 设置一个超大值，以保证滚动条滚动到底部
							// 	duration: 0
							// });
							this.setScrollIntoView()
						})
					})

				})
			},
			copy() {

				if (this.info.list.WeChat_QR_code) {


					this.showTree = true




				} else if (this.info.list.wechat_number) {
					uni.setClipboardData({
						data: this.info.list.wechat_number,
						success: function() {
							uni.showToast({
								duration: 3000,
								title: "已复制微信号!",
								icon: 'none'
							})
						}
					});
				} else {
					uni.showToast({
						duration: 3000,
						title: "对方未设置微信号！"
					})
				}

			},
			setPhone() {
				uni.makePhoneCall({
					phoneNumber: this.info.list.mobile //仅为示例
				});
			},
			goBack() {
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	@import "./global.scss";

	page {
		background-color: #F5F5F7;
		font-size: 28rpx;
	}


	.slot-content {
		display: flex;
		align-items: center;
		width: 100%;

		.longan {
			display: flex;
			align-items: center;
			width: 100%;
			justify-content: center;

			image {
				width: 36rpx;
				height: 36rpx;
				margin-right: 16rpx;
			}

			text {
				font-size: 32rpx;
				color: #7a7a7a;
			}
		}
	}

	.st2 {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 560rpx;
		height: auto;
		box-sizing: border-box;
		padding: 30rpx;
		background: #fff;
		border-radius: 30rpx;
	}

	.header {
		width: 100%;
		background: white;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;

		.header-content {
			width: calc(100% - 20rpx);
			position: fixed;
			left: 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			//box-sizing: border-box;
			padding-left: 20rpx;

			.header-content-title {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.header-content-title-tx {
					font-family: PingFang SC;
					font-weight: 400;
					font-size: 32rpx;
					color: #292929;
					margin-bottom: 9rpx;
				}

				.header-content-title-subTitle {
					font-family: PingFang SC;
					font-weight: 300;
					font-size: 22rpx;
					color: #999999;
				}
			}

			.header-content-layout {
				width: 96rpx;
			}
		}

		.header-tab {
			width: 100%;
			height: 123rpx;
			border-top: 1rpx solid #CECECE;
			display: flex;
			justify-content: space-between;
			align-items: center;
			box-sizing: border-box;
			padding: 0 80rpx;

			view {
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				width: 100rpx;
				height: 100rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				image {
					width: 50rpx;
					height: 50rpx;
					margin-bottom: 17rpx;
				}

				font-family: PingFang SC;
				font-weight: 300;
				font-size: 24rpx;
				color: #292929;
			}
		}
	}

	.content {
		width: 100%;
		// overflow-y: scroll;
		position: relative;

		.ch {
			position: absolute;
			z-index: 88;
			display: flex;
			flex-direction: column;
			align-items: center;
			bottom: -50rpx;
			z-index: 999;
			right: 200rpx;
			transition: opacity 0.5s ease;

			.sxj {
				border-bottom-color: #fff;
				width: 0;
				height: 0;
				border-left: 8rpx solid transparent;
				border-right: 8rpx solid transparent;
				border-bottom: 10rpx solid rgba(0, 0, 0, 0.7);
			}

			.chbox {
				width: 88rpx;
				height: 44rpx;
				border-radius: 20rpx;
				background: rgba(0, 0, 0, 0.7);
				color: #fff;
				font-size: 24rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		// <view class="ch">
		// 	<view class="sxj"></view>
		// 	<view class="chbox">撤回</view>
		// </view>


	}

	/* 加载数据提示 */
	.tips {
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 110rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		// margin-bottom: constant(safe-area-inset-bottom);
		// margin-bottom: env(safe-area-inset-bottom);
	}

	.box-2 {
		position: fixed;
		left: 0;
		width: 100%;
		bottom: 0;
		height: auto;
		z-index: 2;
		// border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		// background-color: #F3F3F3;

		/* 兼容iPhoneX */
		padding-bottom: 0;
		// padding-bottom: constant(safe-area-inset-bottom);
		// padding-bottom: env(safe-area-inset-bottom);

		.flex_col {
			padding: 0 20rpx;
			height: 110rpx;
		}

		.content {
			background-color: #fff;
			height: 64rpx;
			padding: 0 20rpx;
			border-radius: 32rpx;
			font-size: 28rpx;
		}

		.send {
			width: 142rpx;
			height: 76rpx;
		}

		.expression {
			width: 64rpx;
			height: 64rpx;
			margin: 0 24rpx;
		}
	}

	.talk-list {
		padding-bottom: 20rpx;

		/* 消息项，基础类 */
		.item {
			padding: 40rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}

			.content {
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 32rpx;
					background-color: #fff;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 32rpx;
					background-color: white;
					// overflow: hidden;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid white;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}

	.input {
		display: flex;
		align-items: center;
		background: white;
		height: 100%;
		width: 690rpx;
		margin: 0 auto;
		border-radius: 55rpx;
		box-sizing: border-box;
		padding: 0 19rpx;

		input {
			flex: 1;
		}
	}

	.slot-content-img {
		width: 500rpx;
		box-sizing: border-box;
		padding: 30rpx;
		border-radius: 30rpx;

		image {
			width: 100%;
		}
	}

	.emoji-swiper {
		height: 65vw;
		background: white;
		margin-top: 20rpx;

		swiper-item {
			display: grid;
			grid-template-columns: repeat(6, 1fr);

			view {
				width: 15vw;
				height: 13vw;
				display: flex;
				justify-content: center;
				align-items: center;

				image {
					width: 9vw;
					height: 9vw;
				}
			}
		}
	}

	.scroll-Y {
		// width: 100vw;
		// height: 100vh;
		// position: fixed;
		// top: 0;
		// left: 0;
		// z-index: 9;
		//background: rgba(0,0,0,0.5);
	}

	#gd {
		width: 100%;
		height: 1rpx;
		opacity: 0;
	}
</style>